package com.leo.contentcenter;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.leo.contentcenter.dao.content.ShareMapper;
import com.leo.contentcenter.domain.dto.user.UserDTO;
import com.leo.contentcenter.domain.entity.content.Share;
import com.leo.contentcenter.feignclient.TestBaiduFeignClient;
import com.leo.contentcenter.feignclient.TestUserCenterFeignClient;
import com.leo.contentcenter.sentineltest.TestControllerBlockHandlerClass;
import com.leo.contentcenter.sentineltest.TestControllerFallbackClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RestController
@Slf4j
public class TestController {

    @Autowired(required = false)
    private ShareMapper shareMapper;
    /**
     * spring cloud提供的一个接口，可以用来查询
     */
    @Autowired
    private DiscoveryClient discoveryClient;
    
    @GetMapping("/test")
    public List<Share> testInstert(){
        //1.做插入
        Share share = new Share();
        share.setCreateTime(new Date());
        share.setUpdateTime(new Date());
        share.setTitle("xxx");
        share.setCover("XXX");
        share.setAuthor("leo");
        share.setBuyCount(1);

        this.shareMapper.insertSelective(share);

        //2.做查询：查询当前数据库所有的share select * from share;
        List<Share> shares = this.shareMapper.selectAll();

        return shares;

    }

    /**
     * 测试：服务发现，证明内容中心总能找到用户中心
     * @return 用户中心所有实力的地址信息
     */
    @GetMapping("/test2")
    public List<ServiceInstance> getInstances() {
        //查询指定服务的所有实力的信息
        //支持多种发现组件: consul/eureka/zookeeper
        return this.discoveryClient.getInstances("user-center");
    }

    @Autowired
    private TestUserCenterFeignClient testUserCenterFeignClient;

    @GetMapping("/test-get")
    public UserDTO query(UserDTO userDTO){
        return  testUserCenterFeignClient.query(userDTO);
    }

    @Autowired
    private TestBaiduFeignClient testBaiduFeignClient;

    @GetMapping("/baidu")
    public String baiduIndex() {
        return this.testBaiduFeignClient.index();
    }

    @Autowired
    private TestService testService;

    @GetMapping("/test-a")
    public String testA() {
        this.testService.common();
        return "test-a";
    }

    @GetMapping("/test-b")
    public String testB() {
        this.testService.common();
        return "test-b";
    }

    @GetMapping("/test-hot")
    @SentinelResource("hot")
    public String testHot(@RequestParam(required = false) String a, @RequestParam(required = false) String b) {
        this.testService.common();
        return a + "" + b;
    }

    @GetMapping("/test-add-flow-rule")
    @SentinelResource("hot")
    public String testHot() {
        this.initFlowQpsRule();
        return"success";
    }

    private void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule("/shares/1");
        // set limit qps to 20
        rule.setCount(20);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setLimitApp("default");
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    @GetMapping("/test-sentinel-api")
    public String testSentinelApi(@RequestParam(required = false) String a) {

        String resourceName = "test-sentinel-api";
        // 设置来源
        ContextUtil.enter(resourceName,"test-wfu");

        Entry entry = null;

        // 定义一个sentinel保护的资源，名称是test-sentinel-api
        try {
            entry = SphU.entry(resourceName);
            // 被保护的业务逻辑
            if (StringUtils.isBlank(a)) {
                throw new IllegalArgumentException("a不能为空");
            }
            return a;
        }
        // 如果被保护的资源被限流或者降级了，就会抛BlockException
        catch (BlockException e) {
            log.warn("限流，或者降级了", e);
            return "限流，或者降级了";
        }
        catch (IllegalArgumentException e2) {
            // 统计 IllegalArgumentException【发生的次数、发生的占比 等等】
            Tracer.trace(e2);
            return "参数非法";
        }
        finally {
            if (entry != null) {
                // 推出entry
                entry.exit();
            }
            ContextUtil.exit();
        }
    }

    @GetMapping("/test-sentinel-resource")
    @SentinelResource(
            value = "test-sentinel-resource",
            blockHandler = "block",
            blockHandlerClass = TestControllerBlockHandlerClass.class,
            fallback = "fallback",
            fallbackClass = TestControllerFallbackClass.class)
    public String testSentinelResource(@RequestParam(required = false) String a) {

        // sentinel注解不支持来源

        // sentinel注解可以区分出是限流了还是降级了，用fallback属性

        // 被保护的业务逻辑
        if (StringUtils.isBlank(a)) {
            throw new IllegalArgumentException("a cannot be blank.");
        }

        // 如果被保护的资源被限流或降级了，需要打印日志
        // 可以用blockHandler 指定一个方法名称叫block

        return a;
        // 定义一个sentinel保护的资源，名称是test-sentinel-api

        // SentinelResource 默认 trace所有的Throwable 所以不需要自己进行了

    }

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/test-rest-template-sentinel/{userId}")
    public UserDTO test(@PathVariable Integer userId) {
        //
        return this.restTemplate
                .getForObject(
                        "http://user-center/users/{userId}",
                        UserDTO.class, userId);
    }



}
